package com.xzx.java.kit.basic;

import java.util.Objects;

/**
 * 不可变的类(可缓存)
 *
 * @author xinzhixuan
 * @version V1.0
 * @date 2017/12/17 13:58
 */
public class CacheImmutable {
    // 可缓存对象的数量
    private static final int MAX_SIZE = 10;
    // 使用数组存储缓存的对象
    private static CacheImmutable[] cache = new CacheImmutable[MAX_SIZE];
    // 记录实例缓存在数组中的位置
    private static int pos = 0;
    private final String name;
    private CacheImmutable(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CacheImmutable that = (CacheImmutable) o;
        return Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    @Override
    public String toString() {
        return "CacheImmutable{" + "name='" + name + '\'' + '}';
    }

    public static CacheImmutable valueOf(String name) {
        // 缓存中存在直接返回
        for (CacheImmutable cacheImmutable : cache) {
            if (cacheImmutable!= null && cacheImmutable.name.equals(name)) {
                return cacheImmutable;
            }
        }

        // 缓存满了
        if (pos == MAX_SIZE) {
            cache[0] = new CacheImmutable(name);
            pos = 1;
        } else {
            cache[pos++] = new CacheImmutable(name);
        }
        return cache[pos - 1];
    }

    public static void main(String[] args) {
        CacheImmutable cacheImmutable1 = CacheImmutable.valueOf("hello");
        CacheImmutable cacheImmutable2 = CacheImmutable.valueOf("hello");
        System.out.println(cacheImmutable1 == cacheImmutable2);
    }
}
